<template>
  <div>
    <el-dialog title="新建报销" :visible.sync="showFurther" width="60%" :before-close="closeAll" :close-on-click-modal="false">
      <el-form :model="data" ref="firstStep" label-width="130px" size="small" label-position="right">
        <el-row :gutter="50">
          <div class="down-box">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectKey" :rules="{ required: true, message: '请选择新增项目', trigger: 'blur' }">
                <el-select v-model="data.projectKey" placeholder="请选择" clearable>
                  <el-option v-for="(item, index) in typeList" :key="index" :label="item.projectName" :value="item.projectKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="applyUserName" :rules="{ required: true, message: '请输入申请人', trigger: 'blur' }">
                <el-input v-model="data.applyUserName" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="费用所属月份" prop="feeTime" :rules="{ required: true, message: '请选择', trigger: 'blur' }">
                <el-date-picker
                  v-model="data.feeTime"
                  type="month"
                  value-format="timestamp"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报销总金额" prop="amount" :rules="{ required: true, message: '请输入', trigger: 'blur' }">
                <el-input type="number" v-model="data.amount"></el-input>
              </el-form-item>
            </el-col>
            <!-- 子事项 -->
            <el-col>
              <div class="reimbursement-asset">
                <div class="reimbursement-asset-name">报销事项</div>
                <div>
                  <el-button @click="next()" size="mini" icon="el-icon-plus"> 添加事项 </el-button>
                </div>
              </div>
            </el-col>
            <div v-for="(item,index) in itemList" :key="index" style="margin:0px 20px 0 0px;">
              <el-col :span="11">
                <el-form-item label="选择事项" prop="chargeItemType">
                  <el-select v-model="item.itemKey" placeholder="请选择" clearable prop="chargeItemType" @change="changeItem(item,index)">
                    <el-option v-for="item in chargeItemTypeList" :key="item.chargeItemKey" :label="item.chargeItemAliasName" :value="item.chargeItemKey"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="费用金额">
                  <el-input type="number" v-model="item.amount" :placeholder="item.placeholder" @blur="computeSum"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <div style="display: flex;justify-content: center;flex-direction: column;height:30px;line-height:30px;">
                  <el-button type="text" @click="remove(index)" v-if="index>0"> 删除 </el-button>
                </div>
              </el-col>
            </div>
            <!-- end -->
            <el-col :span="24">
              <el-form-item label="说明">
                <el-input v-model="data.description"></el-input>
              </el-form-item>
            </el-col>
          </div>
          <div class="up-box">
            <el-col :span="24">
              <el-form-item label="审批文件上传">
                <el-upload class="upload-demo"  :file-list="fileList" action="no" :on-remove="handleRemove" :http-request="event => beforeupload(event.file)">
                  <el-button type="primary" plain class="addSpan" style="margin-right: 10px" size="mini">上传附件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
        <el-row type="flex" :justify="'end'">
          <el-button @click="closeAll" round> 取消 </el-button>
          <el-button @click="save('firstStep')" round> 确认 </el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { projectList,uploadPhoto } from '@/api';
import { accAdd } from '@/common/js/utils.js';
import Api from '../api/doWork';
export default {
  components: {},

  data() {
    return {
      showFurther: false,
      typeList:[],
      chargeItemTypeList:[],
      data: {
        projectKey:null,
        applyUserName:JSON.parse(localStorage.getItem('userInfo')).nickname,
        feeTime:null,
        amount:null,
        description:null,
        itemList:[],
        attachmentList:[]
      },
      itemList:[{
         itemKey:'',
         amount:'',
         placeholder:''
      }],
      fileList:[]
    }
  },
  methods: {
    init () {
      this.showFurther = true
      this.getProjectList();
      this.getBusinessMapList()
    },
    handleRemove(file){
      this.data.attachmentList.forEach(((ele,index)=>{
        if(ele.uid == file.uid){
          this.data.attachmentList.splice(index, 1)
        }
      }))
    },
    changeItem(item,index){
      this.chargeItemTypeList.forEach(ele=>{
        if(ele.chargeItemKey == item.itemKey){
          this.itemList[index].placeholder='最大填报金额'+ele.reimbursementLimit
        }
      })
    },
    async getBusinessMapList(){
      const res = await Api.businessMapList({
        bizId:localStorage.getItem('userEnterpriseid'),
        supportReimbursement:1,
        queryLastLevel:1
      });
      this.chargeItemTypeList = res.rows || []
    },
    async getProjectList() {
      const res = await projectList();
      this.typeList = res.rows || []
    },
    next(){
      this.itemList.push({
        itemKey:'',
        amount:''
      })
    },
    remove(index){
      this.itemList.splice(index, 1)
      this.computeSum()
    },
    beforeupload(file, a) {
      uploadPhoto(file).then(res => {
        this.fileList.push(file)
        this.data.attachmentList = [{ fileUrl: res.data.rows[0].url, fileTitle: res.data.rows[0].originalName, fileId: res.data.rows[0].key,uid:file.uid }];
        this.$message.success('上传成功');
      });
    },
    closeAll(){
      this.showFurther = false
      Object.keys(this.data).forEach(key => this.data[key]=null);
      this.itemList=[{itemKey:'',amount:''}]
      this.data.itemList=[]
      this.data.attachmentList=[]
      this.data.applyUserName=JSON.parse(localStorage.getItem('userInfo')).nickname
      this.fileList=[]
    },
    async save(formName){
      let userInfo = JSON.parse(localStorage.getItem('userInfo'))
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          for (let i = 0,len = this.itemList.length; i < len; i++) {
            let item = this.itemList[i]
            if (!item.itemKey) {
              this.$message.warning('请检查事项，不能为空！')
              return
            }
          }
          for (let i = 0,len = this.itemList.length; i < len; i++) {
            let item = this.itemList[i]
            if (!item.amount) {
              this.$message.warning('请检查费用金额，不能为空！')
              return
            }
          }
          this.data.itemList = this.itemList
          this.data.applyUser = userInfo.key
          let res = await Api.reimbursementCreated(this.data)
          this.$message.success('新建成功！')
          this.closeAll()
        }
      });
    },

    //计算总金额
    computeSum(){
      let num = 0
      this.itemList.forEach(item => {
        num = Number(accAdd(num,item.amount))
      })
      this.data.amount = num
    }
  },

};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  .el-dialog__header {
    background: #3384fe;
  }
}
::v-deep .el-button.is-round {
  background-color: #444444;
  color: #fff;
}
::v-deep .payMoney .el-form-item__content {
  display: flex;
  .delSpan {
    cursor: pointer;
    color: #33b5ff;
    width: 50px;
    text-align: right;
  }
}
.down-box{
  .el-col{
    height: 50px!important;
  }
}
.up-box{
  .el-col{
    min-height: 50px!important;
  }
}
.reimbursement-asset{
  display: flex;
  justify-content: space-between;
  padding-left: 10px;
  .reimbursement-asset-name{
    font-size: 16px;
    font-weight: 600;
    line-height: 30px;
    height: 30px;
  }
}
</style>
